extends CharacterBody2D

class_name FishBase

signal FACE_TURN


# === 配置参数 ===
@export var swim_speed: float = 70.0       # 固定游动速度（像素/秒）
@export var min_wander_distance: float = 50 # 最小目标点距离
@export var min_stay_interval:float = 1.0   # 最小等待间
@export var max_stay_interval:float = 10.0   # 最小等待间
@export var tank_rect: Rect2 = Rect2(       # 鱼缸边界（左，上，宽，高）
	50, 50, 
	700, 500
)


# === 基本参数 ===
@export var true_name:String
@export var nick_name:String
@export var price:int
@export var description:String
@export var type_tap:Typetap
@export var friendly:bool
@export var can_be_interact:bool
@export var flip_duration := 0.5 # 翻转时间
@export var base_scale:float = 5.0
@export var abilities:Array[Ability]

@export var animation_sprite_2d:AnimatedSprite2D


# === 运行时变量 ===
var _target_position: Vector2
var _is_moving: bool = false
var face_right:bool = true

	
func _ready() -> void:
	# 初始静止状态
	await get_tree().create_timer(1.0).timeout
	_is_moving = false
	_schedule_new_target()
	
	#start_flip(1)
	

#翻转动画
func start_flip(direction: int): # direction: 1(右转) / -1(左转)
	var animator_mat = animation_sprite_2d.material
	var tween = create_tween()
	tween.set_ease(Tween.EASE_IN_OUT)
	tween.set_trans(Tween.TRANS_SINE)
	tween.tween_property(animator_mat, "shader_parameter/angle", direction * 90.0, flip_duration/2)
	tween.tween_callback(turn_face_opposite)
	tween.tween_property(animator_mat, "shader_parameter/angle", 0.0, flip_duration/2)


#根据自身当前朝向，水平翻转
func turn_face_opposite():
	if face_right == true:
		turn_face_side(-1)
		FACE_TURN.emit(-1)
	else:
		turn_face_side(1)
		FACE_TURN.emit(1)
	
	

#指定方向转向
func turn_face_side(direction:int):
	if direction == 1:
		scale.x = 1
		scale.y = 1
		rotation_degrees = 0 #把翻转值限制在0否则会出bug
		face_right = true
	else:
		scale.x = -1
		scale.y = 1
		rotation_degrees = 0 #把翻转值限制在0否则会出bug
		face_right = false


func _physics_process(delta):
	if !_is_moving:
		return
	
	# 计算方向并立即转向
	var direction = (_target_position - global_position).normalized()
	
	# 设置速度并移动
	velocity = direction * swim_speed
	move_and_slide()
	
	# 到达检测（考虑物理引擎的移动精度）
	if global_position.distance_squared_to(_target_position) < 25:
		_stop_movement()

# 生成新目标并开始移动
func _schedule_new_target():
	var attempt = 0
	while attempt < 5:
		_target_position = Vector2(
			randf_range(tank_rect.position.x, tank_rect.end.x),
			randf_range(tank_rect.position.y, tank_rect.end.y)
		)
		# 验证目标点有效性
		if _is_valid_target():
			_is_moving = true
			check_to_flip()
			return
		attempt += 1
	_stop_movement()

func check_to_flip():
	if (_target_position - global_position).normalized().x <= 0 && face_right:
		start_flip(-1)
	elif (_target_position - global_position).normalized().x > 0 && face_right == false:
		start_flip(1)

# 验证目标点是否符合要求
func _is_valid_target() -> bool:
	return (
		global_position.distance_to(_target_position) > min_wander_distance &&
		tank_rect.has_point(_target_position)
	)

# 停止移动并计划下次行动
func _stop_movement():
	_is_moving = false
	velocity = Vector2.ZERO
	get_tree().create_timer(randf_range(min_stay_interval, max_stay_interval)).timeout.connect(_schedule_new_target)

# 调试绘制
#func _draw():
	#if Engine.is_editor_hint():
		#return
	#draw_line(Vector2.ZERO, Vector2(50, 0).rotated(rotation), Color.YELLOW, 2)
	#draw_circle(_target_position - global_position, 3, Color.RED)
